<template>
  <div class="tag-select">
    <el-select
      v-model="selectedTags"
      multiple
      filterable
      allow-create
      default-first-option
      placeholder="请选择或输入标签，多个标签用逗号分隔"
      style="width: 100%"
      @change="handleChange"
    >
      <el-option
        v-for="item in tagOptions"
        :key="item.labelId"
        :label="item.labelName"
        :value="item.labelName">
      </el-option>
    </el-select>
    <div class="tag-display" v-if="displayTags.length > 0">
      <span 
        v-for="(tag, index) in displayTags" 
        :key="index" 
        class="tag-item"
        :style="{ backgroundColor: tag.color || '#409EFF' }"
      >
        {{ tag.name }}
      </span>
    </div>
  </div>
</template>

<script>
import { listLabel } from "@/api/note/noteLabel";

export default {
  name: "TagSelect",
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      selectedTags: [],
      tagOptions: [],
      displayTags: []
    };
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          this.selectedTags = newVal.split(',').map(tag => tag.trim()).filter(tag => tag);
          this.updateDisplayTags();
        } else {
          this.selectedTags = [];
          this.displayTags = [];
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadTagOptions();
  },
  methods: {
    // 加载标签选项
    async loadTagOptions() {
      try {
        const response = await listLabel({});
        this.tagOptions = response.rows || [];
      } catch (error) {
        console.error("加载标签失败:", error);
      }
    },
    
    // 处理选择变化
    handleChange(value) {
      // 更新显示标签
      this.updateDisplayTags();
      
      // 发送事件通知父组件
      const tagsString = value.join(',');
      this.$emit('input', tagsString);
      this.$emit('change', tagsString);
    },
    
    // 更新显示标签
    updateDisplayTags() {
      this.displayTags = this.selectedTags.map(tagName => {
        // 查找是否有预定义的颜色
        const tagOption = this.tagOptions.find(option => option.labelName === tagName);
        return {
          name: tagName,
          color: tagOption ? tagOption.color : '#409EFF'
        };
      });
    }
  }
};
</script>

<style scoped>
.tag-select {
  width: 100%;
}

.tag-display {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  color: white;
  font-size: 12px;
  font-weight: 500;
}
</style>